<?php

!defined('IN_NOVA') && exit('Access Denied!');

class Admin {

	public function __construct() {}

	public function __destruct() {}

	public function start() {
		global $db,$theme,$cache,$request;
		$id = $request->id;
		switch( $request->get( 'p' ) ) {
		case 'saveadd':
			// 执行保存日志
			$article_id = $this->article_add();
			//$article_type = $request->get( 'article_type', 'P' );
			if( $cache->config['arttype'] == '静态' ){
				page_make( $article_id, $article_type );
			}
			$cache->refresh( 'count', TRUE );
			$cache->refresh( 'article_new', TRUE );
			$cache->refresh( 'article_list', TRUE );
			$theme->show_message( L('_ADD_ARTICLE_SUCCESS_'), $theme->get_blog_info('path') );
			break;
		case 'saveedit':
			// 执行修改日志
			$this->article_edit( $id );
			$article_type = $request->get('article_type','P');
			if( $cache->config['arttype'] == '静态' ){
				page_make( $article_id, $article_type );
			}
			$cache->refresh( 'article_hot', TRUE );
			$cache->refresh( 'article_new', TRUE );
			$cache->refresh( 'article_list', TRUE );
			$theme->show_message( L('_EDIT_ARTICLE_SUCCESS_'), $theme->get_blog_info('path') );
			break;
		case 'top':
			// 执行日志置顶
			$db->query( "UPDATE `" . DB_PREFIX . "article` SET istop = 1 WHERE id=$id" );
			// 删除缓存
			$cache->refresh( 'article_list', TRUE );
			$theme->show_message( '日志置顶成功', $request->get_http_referer() );
			break;
		case 'topcancel':
			// 执行取消日志置顶
			$db->query( "UPDATE `" . DB_PREFIX . "article` SET istop = 0 WHERE id=$id" );
			// 删除缓存
			$cache->refresh( 'article_list', TRUE );
			$theme->show_message( '取消日志置顶成功', $request->get_http_referer() );
			break;
		case 'reflash':
			// 执行刷新日志
			/*page_make_html( $id );
			$db->query( "UPDATE `" . DB_PREFIX . "article` SET `update`=0 WHERE id=$id" );*/
			$theme->show_message( '刷新日志成功', $request->get_http_referer() );
			break;
		case 'del':
			// 执行删除日志
			$category = $db->result( "SELECT category FROM `" . DB_PREFIX . "article` WHERE id=$id AND isdel = 0" );
			if( $category == '' ) {
				$theme->show_message( '日志不存在！' );
				break;
			}
			// 分类计数减一
			$db->query( "UPDATE `" . DB_PREFIX . "category` SET articlenum = articlenum - 1 WHERE cid=$category" );
			// 删除此日志的评论
			$db->query( "UPDATE `" . DB_PREFIX . "comment` SET isdel = 1 WHERE articleid=$id" );
			// 删除对应标签
			$tags = $db->result( "SELECT tag FROM `" . DB_PREFIX . "article` WHERE id=$id" );
			$tags = str_replace( '*}{*',',',$tags );
			$tags = str_replace( '*}','',$tags );
			$tags = str_replace( '{*','',$tags );
			$tags = split( ',' , $tags );
			foreach($tags as $tag){
				if( $tag != '' ){
					$db->query( "UPDATE `" . DB_PREFIX . "tags` SET t_num=t_num-1 WHERE t_id=$tag" );
				}
			}
			// 删除日志
			$db->query( "UPDATE `" . DB_PREFIX . "article` SET isdel = 1 WHERE id=$id" );
			// 删除缓存
			$cache->article_new = NULL;
			$cache->article_hot = NULL;
			$cache->comment_new = NULL;
			$cache->category = NULL;
			$cache->count = NULL;
			$cache->tag = NULL;
			$theme->show_message( '删除日志成功' );
			break;
		case 'addreply':
			// 执行添加回复
			$reply = htmlspecialchars( $request->get('commentreply','P') );
			$reply = str_replace( array("\r\n", "\n", "\r"), '<br />', $reply );
			$db->query( "UPDATE `" . DB_PREFIX . "comment` SET replyuser = '" . $_SESSION['user_name'] . "',reply = '$reply',replytime = " . PHP_TIME . " WHERE cid = $id" );
			$theme->show_message( '添加回复成功', $request->get_http_referer() );
			break;
		case 'delreply':
			// 执行删除回复
			$db->query( "UPDATE `" . DB_PREFIX . "comment` SET replyuser = NULL WHERE cid = $id" );
			$theme->show_message( '删除回复成功' );
			break;
		case 'delcomment':
			// 执行删除评论
			$aid = $db->result( "SELECT articleid FROM `" . DB_PREFIX . "comment` WHERE cid=$id AND isdel = 0" );
			if( $aid == '' ) {
				$theme->show_message( '评论不存在！' );
				break;
			}
			$db->query( "UPDATE `" . DB_PREFIX . "article` SET comment=comment-1 WHERE id=$aid" );
			$db->query( "UPDATE `" . DB_PREFIX . "comment` SET isdel=1 WHERE cid=$id" );
			$cache->article_hot = NULL;
			$cache->comment_new = NULL;
			$cache->guestbook_new = NULL;
			$cache->count = NULL;
			$theme->show_message( '删除评论成功' );
			break;
		case 'censor':
			// 评论审核通过
			$db->query( "UPDATE `" . DB_PREFIX . "comment` SET isshow = 1 WHERE cid = $id" );
			$cache->comment_new = NULL;
			$cache->guestbook_new = NULL;
			$theme->show_message( '审核评论成功', $request->get_http_referer() );
			break;
		case 'edit':
			// 输出日志编辑页
			include( APP_ROOT . 'editor/fckeditor.php' );
			$theme->theme['article'] = $db->fetch_one_array( 'SELECT * FROM `' . DB_PREFIX . 'article` WHERE id=' . $id );
			$theme->theme['article']['trackback'] = '';//$db->result( 'SELECT tb_url FROM `' . DB_PREFIX . 'trackback` WHERE tb_type = 0 AND tb_article_id=' . $id );
			// 处理附件
			$theme->theme['article']['attachment'] = str_replace( '*}{*',',',$theme->theme['article']['attachment']);
			$theme->theme['article']['attachment'] = str_replace( '*}','',$theme->theme['article']['attachment']);
			$theme->theme['article']['attachment'] = str_replace( '{*','',$theme->theme['article']['attachment']);
			$temp = array();
			$temp = split( ',' , $theme->theme['article']['attachment'] );
			$theme->theme['article']['attachment'] = '';
			$blog_path = str_replace( ' ','%20',APP_PATH );
			foreach($temp as $row){
				if( !is_numeric( $row ) ) continue;
				$file_info = $db->fetch_one_array( "SELECT ul_filetype,ul_filepath FROM `" . DB_PREFIX . "upload` WHERE ul_id=$row" );
				if ( stristr( $file_info['ul_filetype'],'image' ) ) {
					$ubb = '<img src=' . $blog_path . $file_info['ul_filepath'] . ' />';
					$ubb2 = '<img src=' . $blog_path . 'include/attachment.php?id=' . $row . ' />';
				} else {
					$ubb = '<span class=download><a href=' . $blog_path . $file_info['ul_filepath'] . ' target=_blank>点击这里下载</a></span>';
					$ubb2 = '<span class=download><a href=' . $blog_path . 'include/attachment.php?id=' . $row . ' target=_blank>点击这里下载</a></span>';
				}
				$theme->theme['article']['attachment'] .= '<li><a href="javascript:;" onclick="to_editor(\''.$ubb2.'\')" title="隐藏附件路径">[防盗链插入]</a> <a href="#" onclick="to_editor(\''.$ubb.'\')" title="显示附件路径">[显式插入]</a> ' . $file_info['ul_filepath'] . '</li>';
			}
			$theme->theme['article']['attachment'] = '<ol>' . $theme->theme['article']['attachment'] . '</ol>';
			// 处理标签
			$theme->theme['article']['tag'] = str_replace( '*}{*',',',$theme->theme['article']['tag']);
			$theme->theme['article']['tag'] = str_replace( '*}','',$theme->theme['article']['tag']);
			$theme->theme['article']['tag'] = str_replace( '{*','',$theme->theme['article']['tag']);
			$temp = array();
			$temp = split( ',' , $theme->theme['article']['tag']);
			$theme->theme['article']['tag'] = '';
			foreach($temp as $row){
				if( isset( $cache->tag[$row]['t_name'] ) ){
					$theme->theme['article']['tag'] .= '{*' . $cache->tag[$row]['t_name'] . '*}';
				}
			}
			$theme->theme['article']['tag'] = str_replace( '*}{*',',',$theme->theme['article']['tag']);
			$theme->theme['article']['tag'] = str_replace( '*}','',$theme->theme['article']['tag']);
			$theme->theme['article']['tag'] = str_replace( '{*','',$theme->theme['article']['tag']);
			// ……
			$theme->theme['article']['p'] = 'saveedit';
			$theme->theme['article']['extra'] = array( 'id' => $id );
			$theme->load('admin');
			break;
		default:
			// 输出日志添加页
			include( APP_ROOT . 'editor/fckeditor.php' );
			$theme->theme['article'] = array();
			$temp = array('title','content','summary','category','tag','trackback','address','keywords','description');
			foreach ( $temp as $value ) {
				$theme->theme['article'][$value] = '';
			}
			$theme->theme['article']['trackback'] = '此功能尚未完成';
			// ……
			$theme->theme['article']['p'] = 'saveadd';
			$theme->theme['article']['extra'] = '';
			$theme->load('admin');
		}
	}

	// 添加一篇日志
	private function article_add(){
		global $cache,$db,$request;
		$title       = $request->get('article_title','P');
		$keywords    = $request->get('article_keywords','P');
		$description = $request->get('article_description','P');
		$content     = $request->get('article_content','P');
		$summary     = $request->get('article_summary','P');
		$address     = $request->get('article_alias','P');
		$type        = $request->get('article_type','P');
		if( trim( $title ) == '' || trim( $content ) == '' ){
			echo "<script language=javascript>alert( '错误：输入内容不完整！' );location.href = 'javascript:history.back()'</script>";
			return;
		}
		if( strlen( $content ) > $cache->config['artmaxlength'] ){
			echo "<script language=javascript>alert( '错误：日志正文不可超过 " . $cache->config['artmaxlength'] . " 字节！' );location.href = 'javascript:history.back()'</script>";
			return;
		}
		if( strlen( $summary ) > $cache->config['artmaxlength'] ){
			echo "<script language=javascript>alert( '错误：日志摘要不可超过 " . $cache->config['artmaxlength'] . " 字节！' );location.href = 'javascript:history.back()'</script>";
			return;
		}
		// 日志别名检查，防止重复
		// 不能为纯数字，防止和系统默认别名重复哦（使用 is_numeric 可能有误伤，不过算了）
		if( is_numeric( $address ) ) {
			echo "<script language=javascript>alert( '错误：日志别名不可以为纯数字！' );location.href = 'javascript:history.back()'</script>";
			return;
		}
		if( $db->result( "SELECT COUNT(id) FROM `" . DB_PREFIX . "article` WHERE address='$address'") ) {
			echo "<script language=javascript>alert( '错误：日志别名已经存在！' );location.href = 'javascript:history.back()'</script>";
			return;
		}
		$file_path = APP_ROOT . '/article/' . $address . '.html';
		@file_put_contents( $file_path, ' ' );
		if( file_exists( $file_path ) ) {
			unlink( $file_path );
		}else{
			echo "<script language=javascript>alert( '错误：日志别名不合法！' );location.href = 'javascript:history.back()'</script>";
			return;
		}
		unset( $file_path );
		// 处理分类
		$category = $request->get('article_category','P');
		$db->query( "UPDATE `" . DB_PREFIX . "category` SET articlenum = articlenum + 1 WHERE cid = '$category'");
		$cache->refresh( 'category', TRUE );

		$type = $request->get('article_type','P');
		$trackback = $request->get('article_trackback','P');

		// 处理标签
		$temp = explode( ',' , $request->get('article_tag','P') );
		$temp = array_unique( $temp );
		$tag = '';
		$find = false;
		foreach( $temp as $itag ){
			if( $itag != '' ){
				foreach( $cache->tag as $tag_id => $tag_arr ){
					if( $tag_arr['t_name'] == $itag ){
						$db->query( "UPDATE `" . DB_PREFIX . "tags` SET t_num = t_num + 1 WHERE t_name = '$itag'");
						$tag .= '{*' . $tag_id . '*}';
						$find = true;
						break;
					}
				}
				if( $find == false ){
					$db->query( "INSERT INTO `" . DB_PREFIX . "tags` (`t_name`,`t_num`) VALUES ('$itag',1)" );
					$tag .= '{*' . $db->insert_id() . '*}';
				}else{
					$find = false;
				}
			}
		}
		$cache->refresh( 'tag', TRUE );

		if( !isset( $_SESSION['upfile'] ) ) $_SESSION['upfile'] = '';
		$db->query( "INSERT INTO `" . DB_PREFIX . "article` (`title`,`keywords`,`description`,`time`,`author`,`category`,`tag`,`summary`,`content`,`read`,`comment`,`address`,`type`,`attachment`) VALUES ('$title', '$keywords', '$description', '" . PHP_TIME . "', '" . $_SESSION['user_name'] . "', $category, '$tag', '$summary', '$content',0,0,'$address','$type','" . $_SESSION['upfile'] . "')" );
		unset($_SESSION['upfile']);
		return $db->insert_id();
	}

	// 修改一篇日志
	private function article_edit( $article_id ){
		global $cache,$db,$request;
		$title = $request->get('article_title','P');
		$keywords = $request->get('article_keywords','P');
		$description = $request->get('article_description','P');
		$content = $request->get('article_content','P');
		$summary = $request->get('article_summary','P');
		$address = trim( $request->get('article_alias','P') );
		$type = $request->get('article_type','P');
		if( trim( $title ) == '' || trim( $content ) == '' ){
			echo "<script language=javascript>alert( '错误：输入内容不完整！' );location.href = 'javascript:history.back()'</script>";
			return;
		}
		if( strlen( $content ) > $cache->config['artmaxlength'] ){
			echo "<script language=javascript>alert( '错误：日志正文不可超过 " . $cache->config['artmaxlength'] . " 字节！' );location.href = 'javascript:history.back()'</script>";
			return;
		}
		if( strlen( $summary ) > $cache->config['artmaxlength'] ){
			echo "<script language=javascript>alert( '错误：日志摘要不可超过 " . $cache->config['artmaxlength'] . " 字节！' );location.href = 'javascript:history.back()'</script>";
			return;
		}
		// 检查文章是否存在
		if( $db->result( "SELECT COUNT(id) FROM `" . DB_PREFIX . "article` WHERE id = $article_id" ) == 0 ){
			$theme->show_message( '哪有这篇文章？您来找找看？' );
			return;
		}
		// 日志别名检查，防止重复
		if( is_numeric( $address ) ) {
			echo "<script language=javascript>alert( '错误：日志别名不可以为纯数字！' );location.href = 'javascript:history.back()'</script>";
			return;
		}
		if( $db->result( "SELECT COUNT(id) FROM `" . DB_PREFIX . "article` WHERE address='$address' AND id<>$article_id") ) {
			echo "<script language=javascript>alert( '错误：日志别名重复！' );location.href = 'javascript:history.back()'</script>";
			return;
		}
		$file_path = APP_ROOT . '/article/' . $address . '.html';
		@file_put_contents( $file_path, ' ' );
		if( file_exists( $file_path ) ) {
			unlink( $file_path );
		}else{
			echo "<script language=javascript>alert( '错误：日志别名不合法！' );location.href = 'javascript:history.back()'</script>";
			return;
		}
		unset( $file_path );
		// 清理旧分类
		$category_old = $db->result( "SELECT category FROM `" . DB_PREFIX . "article` WHERE id = $article_id" );
		$db->query( "UPDATE `" . DB_PREFIX . "category` SET articlenum = articlenum - 1 WHERE cid = $category_old");
		// 处理新分类
		$category = $request->get('article_category','P');
		$db->query( "UPDATE `" . DB_PREFIX . "category` SET articlenum = articlenum + 1 WHERE cid = $category");
		$cache->refresh( 'category', TRUE );

		$type = $request->get('article_type','P');
		$trackback = $request->get('article_trackback','P');

		// 清理旧标签
		$tags_old = $db->result( "SELECT tag FROM `" . DB_PREFIX . "article` WHERE id = $article_id" );
		$tags_old = str_replace( '*}{*',',',$tags_old);
		$tags_old = str_replace( '*}','',$tags_old);
		$tags_old = str_replace( '{*','',$tags_old);
		$tags_old = explode( ',' ,$tags_old );
		foreach( $tags_old as $i_tag ){
			if( $i_tag != '' ){
				$db->query( "UPDATE `" . DB_PREFIX . "tags` SET t_num = t_num - 1 WHERE t_id = $i_tag" );
			}
		}

		// 处理新标签
		$temp = explode( ',' , $request->get('article_tag','P') );
		$temp = array_unique( $temp );
		$tag = '';
		$find = false;
		$tag_list = $db->fetch_all( 'SELECT * FROM `' . DB_PREFIX . 'tags` ORDER BY t_id Asc' );
		foreach( $temp as $itag ){
			if( $itag != '' ){
				foreach( $tag_list as $tag_arr ){
					if( $tag_arr['t_name'] == $itag ){
						$db->query( "UPDATE `" . DB_PREFIX . "tags` SET t_num = t_num + 1 WHERE t_name = '$itag'");
						$tag .= '{*' . $tag_arr['t_id'] . '*}';
						$find = true;
						break;
					}
				}
				if( $find == false ){
					$db->query( "INSERT INTO `" . DB_PREFIX . "tags` (`t_name`,`t_num`) VALUES ('$itag',1)" );
					$tag .= '{*' . $db->insert_id() . '*}';
				}else{
					$find = false;
				}
			}
		}
		$cache->refresh( 'tag', TRUE );

		if( !isset( $_SESSION['upfile'] ) ) $_SESSION['upfile'] = '';
		$upfile = $db->result( "SELECT attachment FROM `" . DB_PREFIX . "article` WHERE id = $article_id" );
		$upfile .= $_SESSION['upfile'];
		$db->query( "UPDATE `" . DB_PREFIX . "article` SET title = '$title' ,keywords= '$keywords',description = '$description', author = '" . $_SESSION['user_name'] . "',category = $category ,tag = '$tag',summary = '$summary',content = '$content',address = '$address',type='$type',attachment='$upfile' WHERE id = $article_id" );
		unset($_SESSION['upfile']);
	}
}
?>